<?php
/**
 * Created by PhpStorm.
 * User: sunku
 * Date: 2017/12/25
 * Time: 9:48
 */

namespace Admin\Logic;
use Admin\Transformer\OrderTransformer;
use Admin\Transformer\OrderBillTransformer;
use Think\Log;
use Think\Model;
use Think\Think;

class OrderLogic extends Model
{
    protected $trueTableName = 'wz_order';

    /**
     * @param $params
     * @return mixed
     */
    public function searchOrderList($params){
        $result = D('Resource/Order','Service')->searchOrderList($params);
        if(is_array($result['orderList']) && count($result['orderList'])){
            foreach ($result['orderList'] as $k=>$order){
                //客户
                $customer = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$order['customer_id']]);
                $result['orderList'][$k]['product_name'] = $customer['product_name'];
                //查询部门信息
                $departmentInfo = D('Resource/User', 'Service')->getDepartmentInfo(['id'=>$order['department_id']]);
                $result['orderList'][$k]['department_name'] = $departmentInfo['name'];
                //产品信息
                $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$order['id']]);
                if(is_array($itemList) && count($itemList)>0){
                    $name = "";
                    foreach ($itemList as $item){
                        $name .= "{$item['first_name']}-{$item['second_name']}-{$item['item_name']},";
                    }
                    $result['orderList'][$k]['category_name'] = $name;
                }
            }
            $tr = new OrderTransformer();
            $result['orderList'] = $tr->TransformerCollection($result['orderList']);
        }
        return $result;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function getOrderDetail($params){
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($params);
        if($orderInfo){
            //admin 信息
            $admin = D('Resource/User','Service')->getUserInfo(['id'=>$orderInfo['admin_id']]);
            $orderInfo['department_name'] = $admin['department_name'];
            //客户信息
            $customer = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$orderInfo['customer_id']]);
            $orderInfo['product_name'] = $customer['product_name'];
            $orderInfo['customer_type'] = $customer['type'];
            $orderInfo['contact_info'] = array(
                '手机' => $customer['mobile'],
                '固话' => $customer['tel'],
                'QQ' => $customer['qq'],
                '微信' => $customer['wechat']
            );
            //first Cate
            $first = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$customer['cid']]);
            //产品信息
            $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$orderInfo['id']]);
            $orderInfo['itemList'] = $itemList;
            $orderInfo['first_name'] = $first['name'];

            $orderTr = new OrderTransformer();
            $orderInfo = $orderTr->transformer($orderInfo);
			//加载发票信息
			$orderBillInfo = D('Resource/OrderBill','Service')->getOrderBillInfo(['order_id'=>$orderInfo['order_id']]);
			$orderBillTr = new OrderBillTransformer();
            $orderBillInfo = $orderBillTr->transformer($orderBillInfo);
			$orderInfo['order_bill'] = $orderBillInfo;
        }
        return $orderInfo;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function getOrderInfo($params)
    {
        $orderInfo = D('Resource/Order', 'Service')->getOrderInfo($params);
        return $orderInfo;
    }

    /**
     * 业支受理
     * @param $params
     * @return string
     */
    public function ajaxSaveOrder($params){
        $order_id = intval($params['id']);

        $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$order_id]);
        if(!$orderInfo){
            return Response(2001,'未查询到该订单信息');
        }
        $result = D('Resource/Order','Service')->updateOrderInfo($params);

        if(!$result){
            return Response(2002,'请求失败');
        }else{
            if($orderInfo['status']!=55){
                $data = [];
                $data['uid'] = $orderInfo['admin_id'];
                $data['customer_id'] = $orderInfo['customer_id'];
                $data['message'] = "【已成单】你的订单业务支持部门已受理成单，订单号为：{$orderInfo['order_code']}";
                $data['type'] = 9;
                $data['status'] = 0;
                D('Resource/Message','Service')->addMessage($data);
            }
            return Response(999,'请求成功');
        }
    }
    /**
     * 订单审核
     * @param $params
     * @return string
     * @type string pass：通过 refuse：拒绝
     * @user_group
     *  1	系统管理员
     *  2	业务支持
     *  3	业务员
     *  4	部门经理
     *  5	部门总监
     *  6	部门总经理
     */
    public function orderApproval($params){
        $order_id = intval($params['order_id']);
        $type = strval($params['type']);
        $description = isset($params['description'])?trim(strval($params['description'])):'';
        $uid = intval($params['uid']);
        //用户信息
        $userInfo = D('Resource/User','Service')->getUserInfo(['id'=>$uid]);
        if(!$userInfo){
            return Response(2000,"登录异常，请重新登录");
        }
        //用户组
        $userGroup = D('Resource/User','Service')->getUserRelationGroupInfo(['au.id'=>$uid]);
        $group_id = $userGroup['id'];

        //订单
        $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$order_id]);
        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        if(!in_array($group_id,[4,5,6])){
            return Response(2002,"无该操作权限");
        }
        if($orderInfo['status']<30){
            return Response(2003,'业务员还未完成下单,暂时不能操作');
        }
        $data = [];
        $data['id'] = $order_id;

        $dataM = [];
        $dataM['uid'] = $orderInfo['admin_id'];
        $dataM['customer_id'] = $orderInfo['customer_id'];
        $dataM['type'] = 9;
        $dataM['status'] = 0;

        if($group_id==4){
            if (($orderInfo['status']==35) && ($orderInfo['dp_manager_review']==1)){
                return Response(2005,"你已审核,无需再次操作");
            }elseif($orderInfo['status']>=40){
                return Response(2004,"你已审核,无需再次操作");
            }
            if($type=='pass'){

                $dataM['message'] = "你的订单部门经理已审核通过，订单号为：{$orderInfo['order_code']}";

                $data['dp_manager_review'] = 1;
                $data['status'] = 35;
            }else{
                $dataM['message'] = "你的订单部门经理已拒绝，订单号为：{$orderInfo['order_code']}，原因：{$description}";

                $data['dp_manager_review'] = 2;
                $data['status'] = 35;
                $description && $data['dp_manager_reason'] = $description;
            }
        }elseif ($group_id==5){
            if($orderInfo['status']==30){
                return Response(2006,"请等待部门经理审核后再操作");
            }elseif (($orderInfo['status']==40) && ($orderInfo['director_review']==1)){
                return Response(2005,"你已审核，无需再次操作");
            }elseif($orderInfo['status']>=45){
                return Response(2004,"你已审核，无需再次操作");
            }
            if($type=='pass'){
                $dataM['message'] = "你的订单部门总监已审核通过，订单号为：{$orderInfo['order_code']}";

                $data['director_review'] = 1;
                $data['status'] = 40;
            }else{
                $dataM['message'] = "你的订单部门总监已拒绝，订单号为：{$orderInfo['order_code']}，原因：{$description}";

                $data['director_review'] = 2;
                $data['status'] = 40;
                $description && $data['director_reason'] = $description;
            }
        }else{
            if($orderInfo['status']==30){
                return Response(2006,"请等待部门经理审核后再操作");
            }elseif ($orderInfo['status']==35){
                return Response(2006,"请等待部门总监审核后再操作");
            }elseif (($orderInfo['status']==45) && ($orderInfo['g_manager_review']==1)){
                return Response(2005,"你已审核，无需再次操作");
            }elseif($orderInfo['status']>45){
                return Response(2004,"你已审核，无需再次操作");
            }
            if($type=='pass'){
                $dataM['message'] = "你的订单总经理已审核通过，订单号为：{$orderInfo['order_code']}";

                $data['g_manager_review'] = 1;
                $data['status'] = 45;
            }else{
                $dataM['message'] = "你的订单总经理已拒绝，订单号为：{$orderInfo['order_code']}，原因：{$description}";

                $data['g_manager_review'] = 2;
                $data['status'] = 45;
                $description && $data['g_manager_reason'] = $description;
            }
        }
        $result = D('Resource/Order','Service')->updateOrderInfo($data);
        if(!$result){
            return Response(2006,"网络请求失败");
        }

        D('Resource/Message','Service')->addMessage($dataM);
        return Response(999,"请求成功");
    }
    /**
     * 订单发票审核
     * @param $params
     * @return string
     * @type string pass：通过 refuse：拒绝
     * @user_group
     *  1	系统管理员
     *  2	业务支持
     *  3	业务员
     *  4	部门经理
     *  5	部门总监
     *  6	部门总经理
     */
    public function orderBillApproval($params){
        $bill_id = intval($params['bill_id']);
        $type = strval($params['type']);
        $description = isset($params['description'])?trim(strval($params['description'])):'';
        $uid = intval($params['uid']);
        //用户信息
        $userInfo = D('Resource/User','Service')->getUserInfo(['id'=>$uid]);
        if(!$userInfo){
            return Response(2000,"登录异常，请重新登录");
        }
        //用户组
        $userGroup = D('Resource/User','Service')->getUserRelationGroupInfo(['au.id'=>$uid]);
        $group_id = $userGroup['id'];
        //发票
        $billInfo = D('Resource/OrderBill','Service')->getOrderBillInfo(['id'=>$bill_id]);
        if(!$billInfo){
            return Response(2001,"未查询到该发票信息");
        }
        //订单
        $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$billInfo['order_id']]);
        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        if(!in_array($group_id,[4,5,6])){
            return Response(2002,"无该操作权限");
        }
        $data = [];
        $data['id'] = $bill_id;

        $dataM = [];
        $dataM['uid'] = $orderInfo['admin_id'];
        $dataM['customer_id'] = $orderInfo['customer_id'];
        $dataM['type'] = 9;
        $dataM['status'] = 0;

        if($group_id==4){
            if($billInfo['status']>1){
                return Response(2004,"你已审核，无需再次操作");
            }elseif (($billInfo['status']==1) && ($billInfo['dp_manager_review']==1)){
                return Response(2005,"你已审核，无需再次操作");
            }
            if($type=='pass'){
                $dataM['message'] = "【已审核-部门经理】你的发票申请部门经理已审核通过，订单号为：{$orderInfo['order_code']}";

                $data['dp_manager_review'] = 1;
                $data['status'] = 1;
            }else{
                $dataM['message'] = "【已拒绝-部门经理】你的发票申请部门经理已拒绝，订单号为：{$orderInfo['order_code']}，原因：{$description}";

                $data['dp_manager_review'] = 2;
                $data['status'] = 1;
                $description && $data['dp_manager_reason'] = $description;
            }
        }elseif ($group_id==5){
            if ($billInfo['status']==0){
                return Response(2006,"请等待部门经理审核后再操作");
            }elseif (($billInfo['status']==5) && ($billInfo['director_review']==1)){
                return Response(2005,"你已审核，无需再次操作");
            }elseif ($billInfo['status']>10){
                return Response(2007,"业支已处理，无需再次操作");
            }
            if($type=='pass'){
                $dataM['message'] = "【已审核-部门总监】你的发票申请部门经理已审核通过，订单号为：{$orderInfo['order_code']}";

                $data['director_review'] = 1;
                $data['status'] = 5;
            }else{
                $dataM['message'] = "【已拒绝-部门总监】你的发票申请部门总监已拒绝，订单号为：{$orderInfo['order_code']}，原因：{$description}";

                $data['director_review'] = 2;
                $data['status'] = 5;
                $description && $data['director_reason'] = $description;
            }
        }else{
            if($billInfo['status']==0){
                return Response(2006,"请等待部门经理审核后再操作");
            }elseif($billInfo['status']==1){
                return Response(2006,"请等待部门总监审核后再操作");
            }elseif (($billInfo['status']==10) && ($billInfo['g_manager_review']==1)){
                return Response(2005,"你已审核，无需再次操作");
            }elseif ($billInfo['status']>10){
                return Response(2007,"业支已处理，无需再次操作");
            }
            if($type=='pass'){
                $dataM['message'] = "【已审核-总经理】你的发票申请总经理已审核通过，订单号为：{$orderInfo['order_code']}";

                $data['g_manager_review'] = 1;
                $data['status'] = 10;
            }else{
                $dataM['message'] = "【已拒绝-总经理】你的发票申请总经理已拒绝，订单号为：{$orderInfo['order_code']}，原因：{$description}";

                $data['g_manager_review'] = 2;
                $data['status'] = 10;
                $description && $data['g_manager_reason'] = $description;
            }
        }
        $result = D('Resource/OrderBill','Service')->updateOrderBillInfo($data);
        if(!$result){
            return Response(2006,"网络请求失败");
        }
        D('Resource/Message','Service')->addMessage($dataM);
        return Response(999,"请求成功");
    }

    /**
     * @param $params
     * @return string
     */
    public function addOrderByCustomer($params){
        $customer_id = intval($params['customer_id']);
        $order_id = isset($params['order_id'])?intval($params['order_id']):'';
        $admin_id = intval($params['admin_id']);
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$customer_id]);
        if(!$customerInfo){
            return Response(2001,"未查询到该用户信息");
        }
        if($customerInfo['status']!=1){
            return Response(2005,"该客户状态暂时无法下单");
        }
        if($customerInfo['phase']<5){
            return Response(2003,"请更新客户阶段");

        }
        if($customerInfo['admin_id']!=$admin_id){
            return Response(2002,"无该执行权限");
        }
        $data = [];
        $data['customer_id'] = $customer_id;
        $data['admin_id'] = $admin_id;
        $data['status'] = ['neq',-1];
        $order_id && $data['order_id'] = $order_id;
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

        if(!$orderInfo){
            $admin = D('Resource/User','Service')->getUserInfo(['id'=>$admin_id]);
            $order = [];
            $order['order_code'] = create_unique_order_id();
            $order['admin_id'] = $admin_id;
            $order['admin_name'] = $admin['name'];
            $order['customer_id'] = $customerInfo['id'];
            $order['department_id'] = $admin['department_id'];
            $order['company_name'] = $customerInfo['company_name'];
            $order['product_name'] = $customerInfo['product_name'];
            $order['mobile'] = $customerInfo['mobile'];
            $order['name'] = $customerInfo['name'];

            $id = D('Resource/Order','Service')->addOrder($order);
            if(!$id){
                return Response(2003,"网络异常，请重试");
            }
            $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$id]);
        }
        return Response(999,"请求成功",['orderInfo'=>$orderInfo]);
    }

    /**
     * 编辑订单商品
     * @param $params
     * @return string
     */
    public function saveOrderItem($params){
        $id = isset($params['id'])?intval($params['id']):'';
        $order_id = isset($params['order_id'])?intval($params['order_id']):'';
        $item_id = isset($params['item_id'])?intval($params['item_id']):'';
        $parent_cid = isset($params['parent_cid'])?intval($params['parent_cid']):'';
        $second_cid = isset($params['second_cid'])?intval($params['second_cid']):'';
        $three_cid = isset($params['three_cid'])?intval($params['three_cid']):'';
        $price = isset($params['price'])?floatval($params['price']):'';
        $quoted_price = isset($params['quoted_price'])?floatval($params['quoted_price']):'';
        $total_price = isset($params['total_price'])?floatval($params['total_price']):'';
        $phase = isset($params['phase'])?intval($params['phase']):'';
        $status = isset($params['status'])?intval($params['status']):1;
        $eid = isset($params['eid'])?intval($params['eid']):0;
        $s_data = isset($params['s_data'])?strval($params['s_data']):'';
        $promote_product = isset($params['promote_product'])?strval($params['promote_product']):'';
        $quoted_type = isset($params['quoted_type'])?intval($params['quoted_type']):'';
        $advertiser = isset($params['advertiser'])?strval($params['advertiser']):'';
        $post_bar = isset($params['post_bar'])?strval($params['post_bar']):'';
        $trade = isset($params['trade'])?strval($params['trade']):'';
        $port = isset($params['port'])?strval($params['port']):'';
        $place = isset($params['place'])?strval($params['place']):'';
        $put_time = isset($params['put_time'])?strval($params['put_time']):'';
        //订单信息
        $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$order_id]);

        if(!$orderInfo){
            return Response(2001,'暂无查询到该订单信息');
        }
        if(!$eid){
            $enquiryInfo = D('Resource/Enquiry','Service')->getItemEnquiryBySql(['item_id'=>$item_id]);
            if($enquiryInfo){
                $eid = $enquiryInfo[0]['id'];
            }
        }
        $itemInfo = D('Resource/Item','Service')->getItemInfo(['id'=>$item_id]);
        //投放时间
        $day = explode('-',$put_time);
        $put_day = count_days($day[0],$day[1])+1;

        $data = [];
        $data['order_id'] = $order_id;
        $data['order_code'] = $orderInfo['order_code'];
        $data['item_id'] = $item_id;
        $data['item_name'] = $itemInfo['name'];
        $parent_cid && $data['parent_cid'] = $parent_cid;
        $second_cid && $data['second_cid'] = $second_cid;
        $three_cid && $data['three_cid'] = $three_cid;
        $status && $data['status'] = $status;
        $data['eid'] = $eid;
        $price && $data['price'] = $price;
        $quoted_price && $data['quoted_price'] = $quoted_price;
        $total_price && $data['total_price'] = $total_price;
        $phase && $data['phase'] = $phase;
        $s_data && $data['s_data'] = $s_data;
        $quoted_type && $data['quoted_type'] = $quoted_type;
        $promote_product && $data['promote_product'] = $promote_product;
        $advertiser && $data['advertiser'] = $advertiser;
        $trade && $data['trade'] = $trade;
        $port && $data['port'] = $port;
        $place && $data['place'] = $place;
        $post_bar && $data['post_bar'] = $post_bar;
        $put_time && $data['put_time'] = $put_time;
        $put_day && $data['put_day'] = $put_day;

        if(!$id){
            $result = D('Resource/OrderItem','Service')->addOrderItem($data);
        }else{
            $data['id'] = $id;
            $result = D('Resource/OrderItem','Service')->updateOrderItemInfo($data);
        }

        if(!$result){
           return Response(2003,"网络请求失败");
        }else{
            return Response(999,"请求成功");
        }
    }

    /**
     * @param $params
     * @return string
     */
    public function ajaxDeleteOrderItem($params){
        $id = intval($params['id']);
        $order_id = intval($params['order_id']);

        //订单信息
        $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$order_id]);
        if(!$orderInfo){
            return Response(2001,'暂无查询到该订单信息');
        }

        //订单项目信息
        $orderItem = D('Resource/OrderItem','Service')->getOrderItemInfo(['id'=>$id]);
        if(!$orderItem){
            return Response(2002,'暂无查询到该订单项目信息');
        }

        if(intval($orderItem['quoted_price'])==0){
            $result = D('Resource/OrderItem','Service')->deleteOrderItem(['id'=>$id]);
        }else{
            $order_price = floatval($orderInfo['amount']-$orderItem['quoted_price']);
            $data = [];
            $data['amount'] = $order_price;
            $data['quoted_price'] = $order_price;
            $data['id'] = $order_id;

            $res = D('Resource/Order','Service')->updateOrderInfo($data);

            if(!$res){
                return Response(2003,"网络请求失败");
            }
            $result = D('Resource/OrderItem','Service')->deleteOrderItem(['id'=>$id]);
        }

        if(!$result){
            return Response(2004,"网络请求失败");
        }
        return Response(999,"请求成功");
    }

    /**
     * 申请报价
     * @param $params
     * @return string
     */
    public function applyQuoted($params){
        $uid = intval($params['uid']);
        $order_id = intval($params['order_id']);

        $data = [];
        $data['id'] = $order_id;
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        //客户信息
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$orderInfo['customer_id']]);
        if($customerInfo['phase']<10){
            return Response(2006,"请跟进客户阶段");
        }
        if($uid!=$orderInfo['admin_id']){
            return Response(2003,"无该操作权限");
        }

        if(!in_array(intval($orderInfo['status']),[-15,-10,0,1,5,10,15])){
            return Response(2004,"该订单已处理，无法申请报价");
        }

        $arr = [];
        $arr['id'] = $order_id;
        $arr['status'] = 5;

        $result = D('Resource/Order','Service')->updateOrderInfo($arr);
        if(!$result){
            return Response(2005,"网络请求失败");
        }
        $dataM = [];
        $dataM['uid'] = 0;
        $dataM['customer_id'] = $orderInfo['customer_id'];
        $dataM['type'] = 7;
        $dataM['status'] = 0;
        $dataM['message'] = "{$orderInfo['admin_name']}申请订单报价，订单号为：{$orderInfo['order_code']}";

        D('Resource/Message','Service')->addMessage($dataM);

        return Response(999,"请求成功");
    }
    /**
     * 申请排期
     * @param $params
     * @return string
     */
    public function applySchedule($params){
        $uid = intval($params['uid']);
        $order_id = intval($params['order_id']);

        $data = [];
        $data['id'] = $order_id;
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        //客户信息
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$orderInfo['customer_id']]);
        if($customerInfo['phase']!=15){
            return Response(2006,"请跟进客户阶段");
        }
        if($uid!=$orderInfo['admin_id']){
            return Response(2003,"无该操作权限");
        }
//        if($orderInfo['status']<15){
//            return Response(2004,"该订单还未完成报价，无法申请排期");
//        }
        if($orderInfo['status']>15){
            return Response(2004,"该订单已申请排期，无需重复操作");
        }

        $sCate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$customerInfo['second_cid']]);
        if($sCate && ($sCate['is_enquiry']==1)){
            $status = intval($orderInfo['status']);
            if($status<15 && $status != -15){
                return Response(2004,"该订单还未完成报价，无法申请排期");
            }
            $str = [];
            $str['order_id'] = $order_id;
            $str['quoted_type'] = ['in',[0,1,2]];
            $str['total_price'] = ['elt',0];
            $orderItemCount = D('Resource/OrderItem','Service')->getOrderItemCount($str);
            if($orderItemCount>0){
                return Response(2006,"有未报价产品，暂不能申请排期");
            }
        }

        $arr = [];
        $arr['id'] = $order_id;
        $arr['status'] = 20;

        $result = D('Resource/Order','Service')->updateOrderInfo($arr);
        if(!$result){
            return Response(2005,"网络请求失败");
        }
        $dataM = [];
        $dataM['uid'] = 0;
        $dataM['customer_id'] = $orderInfo['customer_id'];
        $dataM['type'] = 9;
        $dataM['status'] = 0;
        $dataM['message'] = "{$orderInfo['admin_name']}申请订单排期，订单号为：{$orderInfo['order_code']}";

        D('Resource/Message','Service')->addMessage($dataM);

        return Response(999,"请求成功");
    }

    /**
     * 直接下单
     * @param $params
     * @return string
     */
    public function orderDirectOrder($params){
        $uid = intval($params['uid']);
        $order_id = intval($params['order_id']);

        $data = [];
        $data['id'] = $order_id;
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        //客户信息
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$orderInfo['customer_id']]);
        if($customerInfo['phase']<15){
            return Response(2006,"请跟进客户阶段");
        }
        if($uid!=$orderInfo['admin_id']){
            return Response(2003,"无该操作权限");
        }

        $sCate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$customerInfo['second_cid']]);
        if($sCate && ($sCate['is_enquiry']==1)){
           if($orderInfo['status']<5){
                return Response(2004,"请申请报价");
           }
            if($orderInfo['status']==5){
                return Response(2005,"请等待报价确认");
            }
        }
        if($sCate && ($sCate['is_schedule']==1)){
           if($orderInfo['status']<20){
                return Response(2007,"请申请排期");
           }
           if($orderInfo['status']==20){
                return Response(2008,"请等待排期确认");
           }
        }
        if($orderInfo['status']>25){
            return Response(2009,"该订单已处理，请勿重复操作");
        }
        $arr = [];
        $arr['id'] = $order_id;
        $arr['status'] = 25;

        $result = D('Resource/Order','Service')->updateOrderInfo($arr);
        if(!$result){
            return Response(2005,"网络请求失败");
        }

        return Response(999,"请求成功");
    }

    /**
     * 终止服务（订单完成）
     * @param $params
     * @return string
     */
    public function orderServiceCompletion($params){
        $uid = intval($params['uid']);
        $order_id = intval($params['order_id']);

        $data = [];
        $data['id'] = $order_id;
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        //客户信息
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$orderInfo['customer_id']]);
        if(!$customerInfo){
            return Response(2006,"客户信息异常");
        }
        if($uid!=$orderInfo['admin_id']){
            return Response(2003,"无该操作权限");
        }
        if($orderInfo['status']>45){
            return Response(2004,"业支已受理，无法终止服务");
        }

        $arr = [];
        $arr['id'] = $order_id;
        $arr['status'] = -1;

        $result = D('Resource/Order','Service')->updateOrderInfo($arr);
        if(!$result){
            return Response(2005,"网络请求失败");
        }
        return Response(999,"请求成功");
    }

    /**
     * 业务员订单完善
     * @param $params
     * @return string
     */
    public function ajaxToSaveOrder($params){
        $order_id = intval($params['id']);
        $uid = intval($params['uid']);
        $is_pay = intval($params['is_pay']);
        $data = [];
        $data['id'] = $order_id;
        $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

        if(!$orderInfo){
            return Response(2001,"未查询到该订单信息");
        }
        //客户信息
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$orderInfo['customer_id']]);
        if(!$customerInfo){
            return Response(2006,"客户信息异常");
        }
        if($uid!=$orderInfo['admin_id']){
            return Response(2003,"无该操作权限");
        }
        if($orderInfo['status']<25){
            return Response(2004,"业支未排期，无法完善订单");
        }
        if($orderInfo['status']>30){
            return Response(2004,"订单正在处理中");
        }
        if(isset($is_pay) && $is_pay){
            $params['status'] = 45;
            $params['director_review'] = 1;
            $params['g_manager_review'] = 1;
            $params['dp_manager_review'] = 1;
        }
        $result = D('Resource/Order','Service')->updateOrderInfo($params);
        if(!$result){
            return Response(2005,"网络请求失败");
        }
        return Response(999,"请求成功");
    }

    /**
     * 订单报价
     * @param $params
     * @return mixed
     */
    public function searchQuotedOrderList($params){
        $result = D('Resource/Order','Service')->searchOrderList($params);
        if(is_array($result['orderList']) && count($result['orderList'])){
            foreach ($result['orderList'] as $k=>$order){
                //客户
                $customer = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$order['customer_id']]);
                $result['orderList'][$k]['product_name'] = $customer['product_name'];
                $result['orderList'][$k]['customer_type'] = $customer['type'];
                //查询部门信息
                $departmentInfo = D('Resource/User', 'Service')->getDepartmentInfo(['id'=>$order['department_id']]);
                $result['orderList'][$k]['department_name'] = $departmentInfo['name'];
                //订单项目
                $order_Num = D('Resource/OrderItem')->getOrderItemCount(['order_id'=>$order['id']]);
                $result['orderList'][$k]['item_num'] = $order_Num;
                //产品信息
                $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$order['id']]);
                if(is_array($itemList) && count($itemList)>0){
                    $name = "";
                    foreach ($itemList as $item){
                        $name .= "{$item['first_name']}-{$item['second_name']}-{$item['item_name']},";
                    }
                    $result['orderList'][$k]['category_name'] = $name;
                }
            }
            $tr = new OrderTransformer();
            $result['orderList'] = $tr->TransformerCollection($result['orderList']);
        }
        return $result;
    }
    /**
     * @param $params
     * @return mixed
     */
    public function searchApprovalOrderList($params){
        $uid = $params['uid'];

        $userDepartmentIdList = D('Resource/UserDepartment', 'Service')->getUserRelationDepartmentIdList($uid);

        if(!$params['department_id']){
            $params['department_id']  = ['in',$userDepartmentIdList];
        }
        unset($params['uid']);

        $result = D('Resource/Order','Service')->searchOrderList($params);
        if(is_array($result['orderList']) && count($result['orderList'])){
            foreach ($result['orderList'] as $k=>$order){
                //客户
                $customer = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$order['customer_id']]);
                $result['orderList'][$k]['product_name'] = $customer['product_name'];
                //查询部门信息
                $departmentInfo = D('Resource/User', 'Service')->getDepartmentInfo(['id'=>$order['department_id']]);
                $result['orderList'][$k]['department_name'] = $departmentInfo['name'];
                //产品信息
                $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$order['id']]);
                if(is_array($itemList) && count($itemList)>0){
                    $name = "";
                    foreach ($itemList as $item){
                        $name .= "{$item['first_name']}-{$item['second_name']}-{$item['item_name']},";
                    }
                    $result['orderList'][$k]['category_name'] = $name;
                }
            }
            $tr = new OrderTransformer();
            $result['orderList'] = $tr->TransformerCollection($result['orderList']);
        }
        return $result;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function exportOrderData($params){
        $result = D('Resource/Order','Service')->getAllOrderList($params);
        $res = [];
        $billType = C('BILL_TYPE');
        $order_statusList = C('ORDER_STATUS');
        $res[] = array('入录时间','更新时间','掉入库时间','订单状态','部门','部门人员','广告主名称','到款公司名称','联系方式','联系人','一级分类','二级分类','三级分类','销售金额','支付金额','其他费用','毛利','账户充值金额','返点','推广产品','用户名','下单时间','账期','下单预计到款时间','预计出账时间','支付时间','支付公司','渠道供应商','上线开始时间','上线结束时间','订单号','合同编号','供应商合同号','到款时间','入账公司','到款公司','到款金额','开票日期','销售发票号','发票类型','发票金额','发票内容','提前开票到款时间','进项登记时间','进项发票号','进项开票类型','进项开票内容','进项开票备注');

        if(is_array($result) && count($result)){
            foreach ($result as $k=>$order){
                //产品信息
                $name = "";
                $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$order['id']]);
                if(is_array($itemList) && count($itemList)>0){
                    foreach ($itemList as $item){
                        $name .= "-{$item['three_name']}";
                    }
                }
                //三级分类
                $three_name = $name;
                //投放时间
                $put_time = $itemList[0]['phase'];
                $st = '无';
                $et = '无';
                if($put_time){
                    $xx = explode('-',$put_time);
                    $st = $xx[0];
                    $et = $xx[1];
                }
                //客户
                $customer = D('Resource/Customer','Service')->getCustomerDetail(['id'=>$order['customer_id']]);
                //查询部门信息
                $departmentInfo = D('Resource/User', 'Service')->getDepartmentInfo(['id'=>$order['department_id']]);
                //发票
                $bill = D('Resource/OrderBill','Service')->getOrderBillInfo(['order_id'=>$order['id']]);
                $contact= '手机:'.$customer['mobile']. '固话:'.$customer['tel']. 'QQ:'.$customer['qq']. '微信:'. $customer['wechat'];
                //预计出账时间
                $x_time = $order['update_time'] + $order['pay_interval']*30*24*60*60;
                $out_time = date('Y-m-d',$x_time);
                $res[] = array(
                    'customer_create_time' => date('Y-m-d',$customer['create_time']),
                    'customer_update_time' => date('Y-m-d',$customer['update_time']),
                    'customer_archive_time' => $customer['archive_time']?date('Y-m-d',$customer['archive_time']):'',
                    'order_status' => $order_statusList[$order['status']],
                    'department_name' => $departmentInfo['name'],
                    'admin_name' => $order['admin_name'],
                    'company_name'=> $customer['company_name'],
                    'o_company_name'=> $order['company_name'],
                    'contact'=> $contact,
                    'contact_name'=> $customer['name'],
                    'first_name' => $customer['first_name'],
                    'second_name' => $customer['second_name']?$customer['second_name']:'无',
                    'three_name' => $three_name?$three_name:"无",
                    'amount' => $order['amount'],
                    'quoted_price' => $order['quoted_price'],
                    'other_price' => $order['other_price'],
                    'profit_price' => $order['profit_price'],
                    'rebate' => $order['rebate'],
                    'product_name'=> $customer['product_name'],
                    'order_time' => $order['order_time']?date("Y-m-d",$order['order_time']):'',
                    'pay_interval' => $order['pay_interval']."个月",
                    'out_pay_interval' => $out_time,
                    'pay_time' => $order['pay_time']?date("Y-m-d",$order['pay_time']):'',
                    'p_company_name' => $order['company_name'],
                    'ditch_company' => $order['ditch_company'],
                    'st' => $st,
                    'et' => $et,
                    'order_code' => $order['order_code'],
                    'protocol_number' => $order['protocol_number'],
                    'e_pay_time' => $order['pay_time']?date("Y-m-d",$order['pay_time']):'',
                    'e_account_company' => $order['account_company'],
                    'e_pay_company' => $order['pay_company'],
                    'e_pay_amount' => $order['pay_amount'],
                    'bill_time' => isset($bill)?date("Y-m-d",$bill['create_time']):'',
                    'bill_no' => isset($bill)?$bill['bill_no']:'',
                    'bill_type' => isset($bill)?$billType[$bill['type']]:'',
                    'bill_amount' => isset($bill)?$bill['amount']:'',
                    'bill_desc' => isset($bill)?$bill['description']:'',
                    'arrival_time' => ($bill['arrival_time'])?date("Y-m-d",$bill['arrival_time']):'',
                    'receipts_time' => ($bill['receipts_time'])?date("Y-m-d",$bill['receipts_time']):'',
                    'receipts_no' => isset($bill)?$bill['receipts_no']:'',
                    'receipts_type' => isset($bill)?$bill['receipts_type']:'',
                    'receipts_desc' => isset($bill)?$bill['receipts_desc']:'',
                    'receipts_remark' => isset($bill)?$bill['receipts_remark']:''
                );
            }
        }
        return $res;
    }

    /**
     * @param $params
     * @return string
     */
    public function ajaxChangeOrderStatus($params){
        $order_id = intval($params['order_id']);
        $type = isset($params['type'])?strval($params['type']):'accept';

        $orderInfo = D('Resource/Order','Service')->getOrderInfo(['id'=>$order_id]);
        if(!$orderInfo){
            return Response(2001,'未查询到该订单信息');
        }

        $data_o = [];
        $data_o['id'] = $order_id;
        $data_o['status'] = 50;
        if($type=='accept'){
            $data_o['status'] = 50;
        }elseif ($type=='refuse'){
            $data_o['status'] = -5;
            $data_o['refuse_accept_reason'] = $params['refuse_accept_reason'];
        }elseif ($type=='success'){
            $data_o['status'] = 55;
        }elseif ($type=='reset'){
            $data_o['status'] = 25;
        }
        $result = D('Resource/Order','Service')->updateOrderInfo($data_o);

        if(!$result){
            return Response(2002,'网络请求失败');
        }else{
            if($type=='accept'){
                $data = [];
                $data['uid'] = $orderInfo['admin_id'];
                $data['customer_id'] = $orderInfo['customer_id'];
                $data['message'] = "【已受理】你的订单业务支持部门已受理，订单号为：{$orderInfo['order_code']}";
                $data['type'] = 9;
                $data['status'] = 0;
                D('Resource/Message','Service')->addMessage($data);
            }elseif($type=='refuse'){
                $data = [];
                $data['uid'] = $orderInfo['admin_id'];
                $data['customer_id'] = $orderInfo['customer_id'];
                $data['message'] = "【拒绝受理】你的订单业务支持部门拒绝受理，订单号为：{$orderInfo['order_code']},";
                $data['type'] = 9;
                $data['status'] = 0;
                D('Resource/Message','Service')->addMessage($data);
            }elseif ($type=='success'){
                //更新客户状态
                D('Resource/Customer','Service')->updateCustomerInfo(['id'=>$orderInfo['customer_id'],'phase'=>20]);
                $data = [];
                $data['uid'] = $orderInfo['admin_id'];
                $data['customer_id'] = $orderInfo['customer_id'];
                $data['message'] = "【已成单】你的订单业务支持部门已受理成单，订单号为：{$orderInfo['order_code']},";
                $data['type'] = 9;
                $data['status'] = 0;
                D('Resource/Message','Service')->addMessage($data);

            }elseif ($type=='reset'){
                $data = [];
                $data['uid'] = $orderInfo['admin_id'];
                $data['customer_id'] = $orderInfo['customer_id'];
                $data['message'] = "【订单重置】你的订单已重置，请检查后重新提交，订单号为：{$orderInfo['order_code']},";
                $data['type'] = 9;
                $data['status'] = 0;
                D('Resource/Message','Service')->addMessage($data);

            }
            return Response(999,"请求成功",['order_id'=>$order_id]);
        }
    }
    /**
     * 管理导出
     * @param $params
     * @return mixed
     */
    public function manageExportOrderData($params){
        $result = D('Resource/Customer','Service')->getAllCustomerList($params);
        $res = [];
        $order_statusList = C('ORDER_STATUS');
        $res[] = array('角色','部门','部门人员','入录时间','更新时间','掉入库时间','订单编号','广告主名称','到款公司名称','一级分类','二级分类','三级分类','销售金额','其他费用','返点','上线开始时间','上线结束时间','推广产品','下单时间','是否到款','账期','状态');

        if(is_array($result) && count($result)){
            foreach ($result as $k=>$customer){
                $data = [];
                $data['customer_id'] = $customer['id'];
                $data['admin_id'] = $customer['admin_id'];
                $data['status'] = ['not in',[-1]];
                $order = D('Resource/Order','Service')->getOrderInfo($data);

                //产品信息
                $name = "";
                $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$order['id']]);
                if(is_array($itemList) && count($itemList)>0){
                    foreach ($itemList as $item){
                        $name .= "-{$item['three_name']}";
                    }
                }
                //三级分类
                $three_name = $name;
                //投放时间
                $put_time = $itemList[0]['phase'];
                $st = '';
                $et = '';
                if($put_time){
                    $xx = explode('-',$put_time);
                    $st = $xx[0];
                    $et = $xx[1];
                }
                $userInfo = D('Resource/User', 'Service')->getUserInfo(['id'=>$customer['admin_id']]);

                //查询部门信息
                $departmentInfo = D('Resource/User', 'Service')->getDepartmentInfo(['id'=>$userInfo['department_id']]);
                //查询用户组信息
                $groupInfo = D('Resource/User', 'Service')->getUserRelationGroupInfo(['au.id'=>$customer['admin_id']]);

                $res[] = array(
                    'group_name' => $groupInfo['name'],
                    'department_name' => $departmentInfo['name'],
                    'admin_name' => $customer['admin_name'],
                    'customer_create_time' => date('Y-m-d',$customer['create_time']),
                    'customer_update_time' => date('Y-m-d',$customer['update_time']),
                    'customer_archive_time' => $customer['archive_time']?date('Y-m-d',$customer['archive_time']):'',
                    'order_code' => $order['order_code'],
                    'company_name'=> $customer['company_name'],
                    'o_company_name'=> $order['company_name'],
                    'first_name' => $customer['first_name'],
                    'second_name' => $customer['second_name']?$customer['second_name']:'',
                    'three_name' => $three_name?$three_name:"",
                    'amount' => $order['amount'],
                    'other_price' => $order['other_price'],
                    'rebate' => $order['rebate'],
                    'st' => $st,
                    'et' => $et,
                    'product_name'=> $customer['product_name'],
                    'order_time' => $order['order_time']?date("Y-m-d",$order['order_time']):'',
                    'is_pay' => ($order['is_pay']==1)?'已到款':'未到款',
                    'pay_interval' => $order['pay_interval']?$order['pay_interval']."个月":'',
                    'order_status' => $order_statusList[$order['status']],
                );
            }
        }
        return $res;
    }
    /**
     * @param $params
     * @return mixed
     */
    public function exportStatCustomerData($params){
        $result = D('Resource/Customer','Service')->getAllCustomerList($params);
        $res = [];
        $billType = C('BILL_TYPE');
        $order_statusList = C('ORDER_STATUS');
         $res[] = array('入录时间','更新时间','掉入库时间','订单状态','部门','部门人员','广告主名称','到款公司名称','联系方式','联系人','一级分类','二级分类','三级分类','销售金额','支付金额','其他费用','毛利','账户充值金额','返点','推广产品','用户名','下单时间','账期','下单预计到款时间','预计出账时间','支付时间','支付公司','渠道供应商','上线开始时间','上线结束时间','订单号','合同编号','供应商合同号','到款时间','入账公司','到款公司','到款金额','开票日期','销售发票号','发票类型','发票金额','发票内容','提前开票到款时间','进项登记时间','进项发票号','进项开票类型','进项开票内容','进项开票备注');

        if(is_array($result) && count($result)){
            foreach ($result as $k=>$customer){
                $data = [];
                $data['customer_id'] = $customer['id'];
                $data['admin_id'] = $customer['admin_id'];
                $data['status'] = ['not in',[-1]];
                $order = D('Resource/Order','Service')->getOrderInfo($data);

                //产品信息
                $name = "";
                $itemList = D('Resource/OrderItem','Service')->getAllOrderItemList(['order_id'=>$order['id']]);
                if(is_array($itemList) && count($itemList)>0){
                    foreach ($itemList as $item){
                        $name .= "-{$item['three_name']}";
                    }
                }
                //三级分类
                $three_name = $name;
                //投放时间
                $put_time = $itemList[0]['phase'];
                $st = '无';
                $et = '无';
                if($put_time){
                    $xx = explode('-',$put_time);
                    $st = $xx[0];
                    $et = $xx[1];
                }
                $userInfo = D('Resource/User', 'Service')->getUserInfo(['id'=>$customer['admin_id']]);
                //查询部门信息
                $departmentInfo = D('Resource/User', 'Service')->getDepartmentInfo(['id'=>$userInfo['department_id']]);
                //发票
                $bill = D('Resource/OrderBill','Service')->getOrderBillInfo(['order_id'=>$order['id']]);
                $contact= '手机:'.$customer['mobile']. '固话:'.$customer['tel']. 'QQ:'.$customer['qq']. '微信:'. $customer['wechat'];
                //预计出账时间
                $x_time = $order['update_time'] + $order['pay_interval']*30*24*60*60;
                $out_time = $x_time?date('Y-m-d',$x_time):'';
                $res[] = array(
                    'customer_create_time' => date('Y-m-d',$customer['create_time']),
                    'customer_update_time' => date('Y-m-d',$customer['update_time']),
                    'customer_archive_time' => $customer['archive_time']?date('Y-m-d',$customer['archive_time']):'',
                    'order_status' => $order_statusList[$order['status']],
                    'department_name' => $departmentInfo['name'],
                    'admin_name' => $order['admin_name'],
                    'company_name'=> $customer['company_name'],
                    'o_company_name'=> $order['company_name'],
                    'contact'=> $contact,
                    'contact_name'=> $customer['name'],
                    'first_name' => $customer['first_name'],
                    'second_name' => $customer['second_name']?$customer['second_name']:'无',
                    'three_name' => $three_name?$three_name:"无",
                    'amount' => $order['amount'],
                    'pay_amount' => $order['pay_amount'],
                    'other_price' => $order['other_price'],
                    'profit_price' => $order['profit_price'],
                    'recharge_price' => $order['recharge_price'],
                    'rebate' => $order['rebate'],
                    'product_name'=> $customer['product_name'],
                    'user_name' => $order['user_name'],
                    'order_time' => $order['order_time']?date("Y-m-d",$order['order_time']):'',
                    'pay_interval' => isset($order['pay_interval'])?$order['pay_interval']."个月":'',
                    'forecast_time' => $order['forecast_time'],
                    'out_pay_interval' => $out_time,
                    'pay_time' => $order['pay_time']?date("Y-m-d",$order['pay_time']):'',
                    'p_company_name' => $order['company_name'],
                    'ditch_company' => $order['ditch_company'],
                    'st' => $st,
                    'et' => $et,
                    'order_code' => $order['order_code'],
                    'protocol_number' => $order['protocol_number'],
                    'contract_number' => $order['contract_number'],
                    'e_pay_time' => $order['pay_time']?date("Y-m-d",$order['pay_time']):'',
                    'e_account_company' => $order['account_company'],
                    'e_pay_company' => $order['pay_company'],
                    'e_pay_amount' => $order['pay_amount'],
                    'bill_time' => isset($bill)?date("Y-m-d",$bill['create_time']):'',
                    'bill_no' => isset($bill)?$bill['bill_no']:'',
                    'bill_type' => isset($bill)?$billType[$bill['type']]:'',
                    'bill_amount' => isset($bill)?$bill['amount']:'',
                    'bill_desc' => isset($bill)?$bill['description']:'',
                    'arrival_time' => ($bill['arrival_time'])?date("Y-m-d",$bill['arrival_time']):'',
                    'receipts_time' => ($bill['receipts_time'])?date("Y-m-d",$bill['receipts_time']):'',
                    'receipts_no' => isset($bill)?$bill['receipts_no']:'',
                    'receipts_type' => isset($bill)?$bill['receipts_type']:'',
                    'receipts_desc' => isset($bill)?$bill['receipts_desc']:'',
                    'receipts_remark' => isset($bill)?$bill['receipts_remark']:''
                );
            }
        }
        return $res;
    }
}